package com.jams.goodox.activity.qa.teacher;

import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;

import org.json.JSONObject;

import butterknife.Bind;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 教师回答的问题  详情
 */
public class TeacherAnswerQuestionDetailActivity extends BaseActivity {

    private static final String TAG = TeacherAnswerQuestionDetailActivity.class.getSimpleName();
    @Bind(R.id.descr)
    TextView descr;
    @Bind(R.id.time)
    TextView time;


    @Bind(R.id.answer_layout)
    LinearLayout answer_layout;

    @Bind(R.id.answerdetail)
    TextView answerdetail;

    @Bind(R.id.check_answer)
    TextView check_answer;


    Question question;

    private boolean isBuy = false;
    private int yangCoin;

    private int teacherId;

    @Override
    protected int getLayoutId() {
        return R.layout.teacher_aqdetail_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this,"问题详情");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部

        question = (Question) getIntent().getSerializableExtra("question");

        if(null != question){
            time.setText(TimeUtils.getDateToString(question.getCreateTime()));
            descr.setText(question.getDescr());
        }else {
            return;
        }

        check_answer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SePref.isLogin()){
                    if(yangCoin >= 0){
                        if(SePref.getCoinCount() >= yangCoin){
                            payAnswer();
                        }else {
                            ToastUtil.show("氧币不足，请先充值!");
                        }
                    }
                }else {
                    ToastUtil.show("请先登录!");
                }
            }
        });

        setUI();

        if(SePref.isLogin()){
            getQuestionDetail();
        }else {
            showAnswer();
        }
    }


    //获取详情 判断是否已经购买
    private void getQuestionDetail(){
        clearMap();

        params.put("requestData", "{" +
                "questionId:" + question.getId() +

                ",memberId:" + SePref.getId()

                        + "}");
        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).questionDetail(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "getQuestionDetai data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));
                        JSONObject object2 = new JSONObject(object.getString("question"));
                        String title_tx = object2.getString("title");
                        String descr_tx = object2.getString("descr");

                        teacherId = object2.getInt("teacherId");
                        isBuy = object.getBoolean("isPay");

                        showAnswer();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }



    //获取问题回答
    private void showAnswer() {
        clearMap();

        params.put("requestData", "{" + "questionId:" + question.getId() + "}");
        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).showAnswer(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "showAnswer data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));

                        yangCoin = object.getInt("yangCoin");

                        check_answer.setText(yangCoin + "氧币查看答案");

                        answerdetail.setText(object.getString("content"));
                        setUI();


                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }

    private void setUI() {
        if(isBuy){
            check_answer.setVisibility(View.GONE);
            answer_layout.setVisibility(View.VISIBLE);
        }else {
            if(yangCoin <= 0){
                check_answer.setVisibility(View.GONE);
                answer_layout.setVisibility(View.VISIBLE);
            }else {
                check_answer.setVisibility(View.VISIBLE);
                answer_layout.setVisibility(View.GONE);
            }
        }
    }

    //购买
    private void payAnswer() {
        clearMap();

        StringBuilder pData = new StringBuilder();
        pData.append("questionId:" + question.getId())
                .append(",coinCount:" + yangCoin)
                .append(",memberId:" + SePref.getId());

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).payAnswer(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "getQuestionDetai data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){

                        if("true".equals(jsonObject.getString("responseData"))){
                            isBuy = true;
                            setUI();
                        }else {
                            ToastUtil.show("购买失败！" );
                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }

}
